import Joi from "joi";
import { ResultSetHeader } from "mysql2";
import { getDB } from "~/server/utils/db/mysql/index";
import { getLoginUid, responseJson } from "~/server/utils/helper/index";
/**
 * 1、判断用户是否登录
 * 2、已登录删除文集
 */

export default defineEventHandler(async (event) => {
  // 1、判断用户是否登录
  let uid = getLoginUid(event);
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请登录", {});
  }

  // 获取客户端传来的手机号和密码
  const body = await readBody(event);

  // 数据校验
  const schema = Joi.object({
    noteId: Joi.number().required(),
  });
  try {
    await schema.validateAsync(body);
  } catch (error) {
    return responseJson(1, "参数错误", {});
  }

  const con = getDB();

  try {
    const [rows] = await con.execute<ResultSetHeader>(
      "DELETE FROM `notes` WHERE `id`=? AND `uid`=?",
      [body.noteId, uid]
    );
    if (rows.affectedRows !== 0) {
      return responseJson(0, "删除成功", {});
    } else {
      return responseJson(1, "文章不存在或无权删除", {});
    }
  } catch (error) {
    console.error("删除文章失败错误详情:", error);
    if (error instanceof Error) {
      console.error("错误消息:", error.message);
      console.error("错误堆栈:", error.stack);
    }
    // @ts-ignore
    setResponseStatus(event, 500);
    return responseJson(1, "删除失败", {});
  }
});
